package com.yxq.mdt.app.modules.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.umeng.socialize.UMShareAPI;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.UmengShareHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.login.bean.UserBean;
import com.yxq.mdt.app.modules.login.model.LoginModel;
import com.yxq.mdt.app.modules.login.presenter.ILoginContract;
import com.yxq.mdt.app.modules.login.presenter.LoginPresenter;
import com.yxq.mdt.app.modules.main.ui.MainActivity;
import com.yxq.mdt.app.modules.personal.bean.MainPersonTokenBean;
import com.yxq.mdt.app.modules.personal.bean.MainPersonalImNumber;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.StringUtils;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 用户登录
 */
@Route(path = RouteTable.ROUTER_ACTIVITY_LOGIN)
public class LoginActivity extends BaseActivity<LoginPresenter> implements ILoginContract.View {

    @BindView(R.id.login_et_account)
    EditText accountEditText;
    @BindView(R.id.login_et_pwd)
    EditText passwordEditText;
    Handler handler = new Handler();
    @BindView(R.id.login_btn_code_login)
    CheckBox loginBtnCodeLogin;
    @BindView(R.id.login_et_code)
    EditText loginEtCode;
    @BindView(R.id.login_iv_code)
    TextView loginIvCode;
    @BindView(R.id.login_layout_code)
    RelativeLayout loginLayoutCode;
    @BindView(R.id.login_layout_pwd)
    RelativeLayout loginLayoutPwd;
    @BindView(R.id.login_btn_register)
    TextView loginBtnRegister;
    CountDownTimer countDownTimer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        mPresenter = new LoginPresenter(this, new LoginModel());
        //隐私登录
        boolean enable = Hawk.get(SPKey.SP_KEY_USER_LOGIN_PRIVACY, false);
        loginBtnCodeLogin.setChecked(enable);
        loginBtnCodeLogin.setOnCheckedChangeListener((compoundButton, b) -> Hawk.put(SPKey.SP_KEY_USER_LOGIN_PRIVACY, b));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //自动登录
        String account = getIntent().getStringExtra("account");
        String pwd = getIntent().getStringExtra("pwd");
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(pwd)) {
            accountEditText.setText(account);
            passwordEditText.setText(pwd);
            login();
        }
        if ("other".equals(getIntent().getStringExtra("login"))) {
            exitDialog();
        }
    }

    /**
     * 弹出其他设备登录提示框
     */
    private void exitDialog() {

        CostumerDialog dialogLogout = new CostumerDialog.Builder(LoginActivity.this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_exit_app_layout)
                .setCancelable(false)
                .create();

        TextView title = dialogLogout.findViewById(R.id.tv_title);

        title.setText("温馨提示");

        TextView content = dialogLogout.findViewById(R.id.tv_content);
        content.setText("您的帐号在其他设备登录");
        TextView cancel = dialogLogout.findViewById(R.id.tv_cancel);
        cancel.setText("确定");
        cancel.setOnClickListener(v -> {
            dialogLogout.dismiss();
        });
        dialogLogout.show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //自动登录
        String account = getIntent().getStringExtra("account");
        String pwd = getIntent().getStringExtra("pwd");
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(pwd)) {
            accountEditText.setText(account);
            passwordEditText.setText(pwd);
            login();
        }
    }

    @OnClick({R.id.login_btn_login, R.id.login_btn_get_pwd, R.id.login_btn_register, R.id.login_iv_wx, R.id.login_iv_qq, R.id.tv_user, R.id.tv_privacy, R.id.login_iv_code})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn_login:
                //登录
                if (loginLayoutCode.getVisibility() == View.VISIBLE) {
                    loginBySMS();
                } else {
                    login();
                }
                break;
            case R.id.login_btn_get_pwd:
                //忘记密码
                Intent intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.login_btn_register:
                //注册
//                intent = new Intent(LoginActivity.this, RegisterActivity.class);
//                startActivity(intent);
//                finish();
                if (loginLayoutCode.getVisibility() == View.VISIBLE) {
                    loginLayoutCode.setVisibility(View.GONE);
                    loginLayoutPwd.setVisibility(View.VISIBLE);
                    loginBtnRegister.setText("验证码登录");
                    findViewById(R.id.login_btn_get_pwd).setVisibility(View.VISIBLE);
                } else {
                    loginLayoutCode.setVisibility(View.VISIBLE);
                    loginLayoutPwd.setVisibility(View.GONE);
                    loginBtnRegister.setText("密码登录");
                    findViewById(R.id.login_btn_get_pwd).setVisibility(View.GONE);
                }
                break;
            case R.id.login_iv_wx:
                //微信登录
                loginWx();
                break;
            case R.id.login_iv_qq:
                //QQ登录
                loginQQ();
                break;
            case R.id.tv_user://用户协议
                intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.USER_AGREEMENT);
                intent.putExtra("title", "用户协议");
                startActivity(intent);
                break;
            case R.id.tv_privacy://隐私协议
                intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PRIVACY_POLICY);
                intent.putExtra("title", "隐私协议");
                startActivity(intent);
                break;
            case R.id.login_iv_code:
                //验证码
                verifyCode();
                break;
        }
    }

    private void verifyCode() {
        if (accountEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入手机号码");
            return;
        }
        if (!StringUtils.isMobileExact(accountEditText.getText().toString())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        showLoadingDialog();
        mPresenter.verifyCode(accountEditText.getText().toString(), 3);
    }

    /**
     * QQ登录
     */
    private void loginQQ() {
        UmengShareHelper.loginQQ(mActivity, new UmengShareHelper.ShareSDKCallback<Map<String, String>>() {
            @Override
            public void onComplete(String name, Map<String, String> stringStringMap) {
                showLoadingDialog();
                mPresenter.loginApp3(stringStringMap.get("uid"), stringStringMap.get("name"), stringStringMap.get("iconurl"), "qq");
            }

            @Override
            public void onError(String errMsg) {
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 微信登录
     */
    private void loginWx() {
        UmengShareHelper.loginWX(mActivity, new UmengShareHelper.ShareSDKCallback<Map<String, String>>() {
            @Override
            public void onComplete(String name, Map<String, String> stringStringMap) {
                showLoadingDialog(false);
                mPresenter.loginApp3(stringStringMap.get("uid"), stringStringMap.get("name"), stringStringMap.get("iconurl"), "wx");
            }

            @Override
            public void onError(String errMsg) {
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 账号密码登录
     */
    private void login() {
        if (accountEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入手机号码");
            return;
        }
        if (passwordEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入密码");
            return;
        }
        if (!StringUtils.isMobileExact(accountEditText.getText().toString())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        showLoadingDialog(false);
        mPresenter.login(accountEditText.getText().toString(), passwordEditText.getText().toString());
    }

    /**
     * 验证码登录
     */
    private void loginBySMS() {
        if (accountEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入手机号码");
            return;
        }
        if (loginEtCode.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入短信验证码");
            return;
        }
        if (!StringUtils.isMobileExact(accountEditText.getText().toString())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        showLoadingDialog(false);
        mPresenter.loginCode(accountEditText.getText().toString(), loginEtCode.getText().toString());
    }

    @Override
    public void onLoginSuccess(UserBean userBean) {
        if (userBean != null) {
            if (userBean.getBlacklist() == 1) {
                hideLoadingDialog();
                //黑名单 不允许登录
                ToastUtils.showShort("您已被禁止登录！");
                return;
            }
            //判断是否需要绑定手机号
            if (StringUtils.isEmpty(userBean.getBinding()) || "null".equals(userBean.getBinding())) {
                hideLoadingDialog();
                //跳转绑定手机号
                startBindPhoneActivity(userBean);
            } else {
                //创建JAVA平台Token
                createToken(userBean);
            }
        } else {
            hideLoadingDialog();
            ToastUtils.showShort("登录失败");
        }
    }

    /**
     * 创建java Token
     */
    private void createToken(UserBean userBean) {
        mPresenter.getTokenData(String.valueOf(userBean.getUserId()), new ApiModel.CommonCallback<MainPersonTokenBean>() {
            @Override
            public void onSuccess(MainPersonTokenBean mainPersonTokenBean) {
                Hawk.delete(SPKey.SP_KEY_USER_INFO_TOKEN);
                Hawk.put(SPKey.SP_KEY_USER_INFO_TOKEN, mainPersonTokenBean);
                //获取环信账号
                getIMInfo(userBean, mainPersonTokenBean);
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 获取环信账号信息
     *
     * @param userBean
     */
    private void getIMInfo(UserBean userBean, MainPersonTokenBean mainPersonTokenBean) {
        //注册环信账号
        mPresenter.getSaveImUser(mainPersonTokenBean.getNickName(), new ApiModel.CommonCallback<MainPersonalImNumber>() {
            @Override
            public void onSuccess(MainPersonalImNumber mainPersonalImNumber) {
                //登录环信
                Hawk.delete(SPKey.SP_KEY_USER_IM_CHAT);
                Hawk.put(SPKey.SP_KEY_USER_IM_CHAT, mainPersonalImNumber);
                loginHx(userBean, mainPersonalImNumber);
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 登录环信
     *
     * @param userBean
     * @param mainPersonalImNumber
     */
    private void loginHx(UserBean userBean, MainPersonalImNumber mainPersonalImNumber) {
        EMClient.getInstance().login(mainPersonalImNumber.getUserName(), mainPersonalImNumber.getPassword(), new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                hideLoadingDialog();
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                startMainActivity(userBean);
            }

            @Override
            public void onProgress(int progress, String status) {
//                ToastUtils.showShort(status);
            }

            @Override
            public void onError(int code, final String message) {
                hideLoadingDialog();
                if (200 == code) {
                    //已经登录
                    startMainActivity(userBean);
                    return;
                }
                ToastUtils.showShort(message + "(" + code + ")");
            }
        });
    }

    /**
     * 跳转绑定手机号码
     *
     * @param userBean
     */
    private void startBindPhoneActivity(UserBean userBean) {
        Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
        intent.putExtra("data", JSON.toJSONString(userBean));
        startActivity(intent);
        finish();
    }

    /**
     * 登录成功 跳转主页
     *
     * @param userBean
     */
    private void startMainActivity(UserBean userBean) {
        Hawk.delete(SPKey.SP_KEY_USER_INFO);
        Hawk.put(SPKey.SP_KEY_USER_INFO, userBean);
        Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
        handler.postDelayed(() -> {
//            if (getIntent().getBooleanExtra("intentMain", true)) {
            //是否需要跳转主页
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
//            }
            finish();
        }, 50);
    }

    @Override
    public void onLoginFailed(String error) {
        hideLoadingDialog();
        ToastUtils.showShort(error);
    }

    @Override
    public void onVerifyCodeSuccess(String info) {

        hideLoadingDialog();
        ToastUtils.showShort("验证码已发送到你手机");
        timer();
    }

    private void stopTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private void timer() {
        stopTimer();
        loginIvCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                loginIvCode.setText((l / 1000) + "s");
            }

            @Override
            public void onFinish() {
                loginIvCode.setText("获取验证码");
                loginIvCode.setEnabled(true);
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void onVerifyCodeFailed(String error) {
        hideLoadingDialog();
        ToastUtils.showShort(error);
    }

    @Override
    public void onRegisterSuccess(String userBean) {

    }

    @Override
    public void onRegisterFailed(String error) {

    }

    @Override
    public void onBindPhoneSuccess(String userBean) {

    }

    @Override
    public void onBindPhoneFailed(String error) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
